package com.lemon.components.tmp.download;

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.StringReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JProgressBar;

public class VideoDownloadHandle {

	int bytesum = 0;
    int byteread = 0;
    
    public void downloadVideo(String m3u8url,String filePath,JProgressBar bar1,JProgressBar bar2){
    	List<String> videoList = buildVideoPlayList(m3u8url);
    	bar1.setMaximum(videoList.size());
    	int i=1;
    	for(String tmp:videoList) {
    		try {
				download(tmp,filePath+"/"+i+".ts",bar2);
				bar1.setValue(i);
				i++;
			} catch (Exception e) {
				e.printStackTrace();
			}
    	}
    }
    
    public List<String> buildVideoPlayList(String m3u8url){
    	List<String> playList = new ArrayList<>();
    	int last = m3u8url.lastIndexOf("/");
    	String prefix = m3u8url.substring(0, last);
    	List<String> uri = m3u8(m3u8url);
    	for(String videoUrl: uri) {
    		playList.add(prefix+"/"+videoUrl);
    	}
    	return playList;
    }
    
    public List<String> m3u8(String m3u8url) {
    	List<String> m3u8List = new ArrayList<String>();
    	try {
			String m3u8 = download(m3u8url);
			BufferedReader bufferedReader = new BufferedReader(new StringReader(m3u8));
			String tmp;
			while ((tmp = bufferedReader.readLine())!=null) {
				if(tmp.indexOf("#") < 0) {
					m3u8List.add(tmp);
				}
			}
			return m3u8List;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
    }
    
    public String download(String urlstr) throws Exception {
		URL url = new URL(urlstr);

		URLConnection conn = url.openConnection();
        InputStream inStream = conn.getInputStream();
        ArrayList<Byte> all = new ArrayList<Byte>();

        byte[] buffer = new byte[1024];
        while ((byteread = inStream.read(buffer)) != -1) {
            bytesum += byteread;
            for(int i=0; i<byteread; i++) {
            	all.add(buffer[i]);
            }
        }
        Byte[] b = all.toArray(new Byte[all.size()]);
        byte[] c = new byte[b.length];
        for(int i=0; i< b.length; i++) {
        	c[i] = b[i];
        }
        return new String(c);
	}
    
	public void download(String urlstr,String savePath,JProgressBar bar) throws Exception {
		URL url = new URL(urlstr);

		URLConnection conn = url.openConnection();
        InputStream inStream = conn.getInputStream();
        bar.setMaximum(inStream.available());
        FileOutputStream fs = new FileOutputStream(savePath);

        byte[] buffer = new byte[1024];
        int readed = 0;
        while ((byteread = inStream.read(buffer)) != -1) {
            bytesum += byteread;
            fs.write(buffer, 0, byteread);
            readed += byteread;
        }
        bar.setValue(readed);
        fs.flush();
        fs.close();
	}
	
//	public static void main(String[] args) throws Exception {
//		VideoDownloadHandle videoDownloadHandle = new VideoDownloadHandle();
//		videoDownloadHandle.downloadVideo(
//				"https://apd-0dba6ef9d781f10cb6b3872795eab173.v.smtcdns.com/omts.tc.qq.com/AxGP0uHEuZ0prJiFKCo-oQeM6wzX7j4xOzy2FYHO6lAA/uwMROfz2r5zCIaQXGdGnC2df644Q3LWUuLvyGY4RMhgE_3T2/AdUD5a1SkmLgrA6KDo_LTId2A4hwDJjX4omoHBppp_yx8tJgbswdNQCWjjw750Z8Ckl4PCOQDSEmLT84EsQyIIOiPP-K2A75XZvD-FR0DZyrpTSp2bakh86gm2hbrr6XAMUHnQfAJfJUii3_JK_w53UYpPPABpci_9NhYn1EksA/p0977iq54s1.321002.ts.m3u8?ver=4"
//				,"d:/新建文件夹");
//	}
}
